package com.tjbaobao.videoplayol.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.tjbaobao.framework.base.BaseItemDecoration;
import com.tjbaobao.framework.base.BaseRecyclerAdapter;
import com.tjbaobao.framework.entity.ui.TitleBarInfo;
import com.tjbaobao.framework.tjbase.TJActivity;
import com.tjbaobao.framework.ui.BaseRecyclerView;
import com.tjbaobao.framework.ui.BaseTitleBar;
import com.tjbaobao.framework.utils.DeviceUtil;
import com.tjbaobao.framework.utils.FileUtil;
import com.tjbaobao.framework.utils.ImageDownloader;
import com.tjbaobao.framework.utils.Tools;
import com.tjbaobao.videoplayol.R;
import com.tjbaobao.videoplayol.base.AppActivity;
import com.tjbaobao.videoplayol.dialog.VideoCacheDialog;
import com.tjbaobao.videoplayol.message.info.VideoInfo;
import com.tjbaobao.videoplayol.message.request.VideoListRequest;
import com.tjbaobao.videoplayol.message.response.VideoListResponse;
import com.tjbaobao.videoplayol.modal.info.VideoCacheInfo;
import com.tjbaobao.videoplayol.utils.BaseAsyncTask;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.paperdb.Paper;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;

public class MainActivity extends AppActivity {

    @BindView(R.id.listView)
    public BaseRecyclerView<Holder,VideoInfo> mRecyclerView ;
    private MyAdapter mAdapter ;
    private ArrayList<VideoInfo> mVideoInfoList = new ArrayList<>();

    @BindView(R.id.swipeRefreshLayout)
    public SwipeRefreshLayout swipeRefreshLayout ;

    private static final String[] PERMISSIONS_VIDEO = {Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO};
    private static final String[] PERMISSIONS_STORAGE= {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static final int REQUEST_VIDEO = 2;

    @Override
    protected void onInitValues(Bundle savedInstanceState) {
        if (!EasyPermissions.hasPermissions(this, PERMISSIONS_STORAGE))
        {
            EasyPermissions.requestPermissions(this, getString(R.string.request_permissions_storage),
                    REQUEST_EXTERNAL_STORAGE, PERMISSIONS_STORAGE);
        }
    }

    @Override
    protected void onInitView() {
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        mRecyclerView.toListView();
        mRecyclerView.addItemDecoration(new ItemDecoration());
        mRecyclerView.setOnItemClickListener(new MyOnItemClickListener());
        mAdapter = new MyAdapter(mVideoInfoList,R.layout.main_list_item_layout);
        mRecyclerView.setAdapter(mAdapter);
        swipeRefreshLayout.setColorSchemeResources(R.color.fw_theme_color,
                R.color.fw_red_off,
                R.color.fw_blue_off,
                R.color.fw_gray);
        swipeRefreshLayout.setOnRefreshListener(new MyOnRefreshListener());
    }

    @Override
    protected void onInitTitleBar(@NonNull BaseTitleBar baseTitleBar) {
        baseTitleBar.setTitle(getString(R.string.main_title));
        baseTitleBar.addImageToRight(R.drawable.ic_new);
    }

    @Override
    protected void onLoadData() {
        new LoadVideoListTask(this,new VideoListRequest()).execute();
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public <V extends TitleBarInfo.BaseView> void onTitleBarClick(int layoutType, int position, V info) {
        if(layoutType==BaseTitleBar.LAYOUT_RIGHT&&position==0) {
            addVideo();
        }
    }

    @AfterPermissionGranted(REQUEST_VIDEO)
    private void addVideo()
    {
        if (EasyPermissions.hasPermissions(this, PERMISSIONS_VIDEO))
        {
            final VideoCacheInfo videoCacheInfo = Paper.book("app").read("videoCacheInfo",null);
            if(videoCacheInfo==null)
            {
                startActivity(VideoRecordActivity.class);
            }
            else
            {
                //还有为上传的视频
                new VideoCacheDialog(context){
                    @Override
                    public void onContinueClick() {
                        super.onContinueClick();
                        //继续上传
                        if(FileUtil.exists(videoCacheInfo.getVideoPath()))
                        {
                            Intent intent = new Intent(MainActivity.this,VideoPreviewActivity.class);
                            intent.putExtra("videoCacheInfo",videoCacheInfo);
                            startActivity(intent);
                        }
                        else
                        {
                            Tools.showToast(getString(R.string.dialog_video_cache_error));
                            Paper.book("app").delete("videoCacheInfo");
                        }
                    }

                    @Override
                    public void onCancel() {
                        super.onCancel();
                        FileUtil.delFileIfExists(videoCacheInfo.getVideoPath());
                        Paper.book("app").delete("videoCacheInfo");
                        //重新录制
                        startActivity(VideoRecordActivity.class);
                    }
                }.show();
            }
        }
        else
        {
            EasyPermissions.requestPermissions(this, getString(R.string.request_permissions_video),
                    REQUEST_VIDEO, PERMISSIONS_VIDEO);
        }
    }

    private class ItemDecoration extends RecyclerView.ItemDecoration
    {
        private int spacingTop = Tools.dpToPx(8);
        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            int position = parent.getChildAdapterPosition(view);
            int itemCount = state.getItemCount();
            if(position!=0)
            {
                outRect.top = spacingTop ;
            }
            if(position==itemCount-1)
            {
                outRect.bottom = spacingTop;
            }
        }
    }

    @SuppressLint("StaticFieldLeak")
    private class LoadVideoListTask extends BaseAsyncTask<VideoListRequest,VideoListResponse>
    {

        LoadVideoListTask(Context context, VideoListRequest request) {
            super(context, request);
        }

        @Override
        protected VideoListResponse getResponse(String resultStr) {
            return new Gson().fromJson(resultStr,VideoListResponse.class);
        }

        @Override
        protected void onSuccess(VideoListResponse response) {
            for(VideoListResponse.Info info: response.getData())
            {
                VideoInfo videoInfo = new VideoInfo();
                videoInfo.setImageUrl(info.imageUrl);
                videoInfo.setTitle(info.title);
                videoInfo.setLikeNum(info.likeCount);
                videoInfo.setPlayNum(info.watchCount);
                mVideoInfoList.add(videoInfo);
            }
            mAdapter.notifyDataSetChanged();
        }
    }

    private class MyAdapter extends BaseRecyclerAdapter<Holder,VideoInfo>
    {
        private ImageDownloader mImageDownloaderUtil = ImageDownloader.getInstance() ;

        MyAdapter(List<VideoInfo> list, int itemLayoutRes) {
            super(list, itemLayoutRes);
            mImageDownloaderUtil.setDefaultImgSize(DeviceUtil.getScreenWidth(),DeviceUtil.getScreenWidth()/2);
        }

        @Override
        public void onBindViewHolder(@NonNull Holder holder, @NonNull VideoInfo videoInfo, int i) {
            mImageDownloaderUtil.load(videoInfo.getImageUrl(),holder.iv_image);
            holder.tv_title.setText(videoInfo.getTitle());
            holder.tv_like.setText(String.format(Locale.getDefault(),"%d", videoInfo.getLikeNum()));
            holder.tv_play_num.setText(String.format(Locale.getDefault(),"%d", videoInfo.getPlayNum()));
        }

        @NonNull
        @Override
        public Holder onGetHolder(View view, int type) {
            return new Holder(view);
        }
    }

    private class Holder extends BaseRecyclerView.BaseViewHolder
    {
        private ImageView iv_image ,iv_user_head;
        private TextView tv_title,tv_user_name,tv_play_num,tv_like ;

        public Holder(View itemView) {
            super(itemView);
        }

        @Override
        public void onInitView(View view) {
            iv_image = view.findViewById(R.id.iv_image);
            iv_user_head = view.findViewById(R.id.iv_user_head);
            tv_title = view.findViewById(R.id.tv_title);
            tv_user_name = view.findViewById(R.id.tv_user_name);
            tv_play_num = view.findViewById(R.id.tv_play_num);
            tv_like = view.findViewById(R.id.tv_like);
        }
    }

    private class MyOnItemClickListener implements BaseRecyclerAdapter.OnItemClickListener<Holder,VideoInfo>
    {
        @Override
        public void onItemClick(@NonNull Holder holder, @NonNull VideoInfo videoInfo, int i) {
            startActivity(VideoDefActivity.class);
        }
    }

    private class MyOnRefreshListener implements SwipeRefreshLayout.OnRefreshListener
    {
        @Override
        public void onRefresh() {
            new Thread(() -> {
                Tools.sleep(3000);
                MainActivity.this.runOnUiThread(() -> swipeRefreshLayout.setRefreshing(false));
            }).start();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }
}
